package com.iot.manage.controller;

import com.alibaba.fastjson.JSONObject;
import com.iot.manage.pojo.App;
import com.iot.manage.pojo.User;
import com.iot.manage.result.Code;
import com.iot.manage.result.Result;
import com.iot.manage.service.TokenService;
import com.iot.manage.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 用户管理控制层
 *
 * @author zhuzhi
 */
@RestController
@RequestMapping("/api/private/v1")
public class UserIotController {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private UserService userService;

    /**
     * 查新用户信息列表
     *
     * @param token
     * @param query 模糊查询登录名关键字
     * @param pagenum 当前页
     * @param pagesize 每页条数
     * @return
     */
    @GetMapping("/users")
    public Result findUsersInfoList(
            @RequestHeader("token") String token,
            @RequestParam("query") String query,
            @RequestParam("pagenum") int pagenum,
            @RequestParam("pagesize") int pagesize) {
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        List<User> usersList;
        int userTotal;
        try{
            usersList = userService.findUsersInfo(query,pagenum,pagesize);
            userTotal = userService.countUsersInfo(query);
        } catch (Exception e){
            e.printStackTrace();
            return result.build(null,Code.D409);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("total",userTotal);
        map.put("pagenum",pagenum);
        map.put("users",usersList);
        return result.build(map, Code.S203);
    }

    /**
     * 新增用户信息
     *
     * @param token
     * @param params 用户信息参数
     * @return
     */
    @PostMapping("/users")
    public Result addUserInfo(
            @RequestHeader("token") String token,
            @RequestBody JSONObject params) {
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        try {
            if(null != findUserInfo(token,params.getString("loginName")).getData()){
                return result.build(null, Code.D403);
            }
            params.put("userId", UUID.randomUUID().toString().replace("-", ""));
            params.put("loginPassMD5", DigestUtils.md5Hex(params.get("loginPass").toString()));
            userService.addUserInfo(params);
        } catch (Exception e) {
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(null, Code.S203);
    }

    /**
     *删除用户信息
     *
     * @param token
     * @param id 用户ID
     * @return
     */
    @DeleteMapping("/users/{id}")
    public Result deleteUserInfo(
            @RequestHeader("token") String token,
            @PathVariable("id") String id) {
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        try {
            userService.deleteUserInfo(id);
            userService.deleteRelevancy(id);
        } catch (Exception e) {
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(null, Code.S204);
    }

    /**
     * 查询用户信息
     *
     * @param token
     * @param param 用户ID
     * @return
     */
    @GetMapping("/users/{id}")
    public Result findUserInfo(
            @RequestHeader("token") String token,
            @PathVariable("id") String param){
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        User user;
        try{
            user = userService.findUserInfo(param);
        } catch (Exception e){
            e.printStackTrace();
            return result.build(null,Code.D408);
        }
        return result.build(user, Code.S205);
    }

    /**
     * 修改用户信息
     *
     * @param token
     * @param id 用户ID
     * @param params 用户信息参数
     * @return
     */
    @PutMapping("/users/{id}")
    public Result updateUserInfo(
            @RequestHeader("token") String token,
            @PathVariable("id") String id,
            @RequestBody JSONObject params){
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        params.put("id",id);
        if (params.get("oldPassword").equals(params.get("loginPass"))){
            params.put("loginPassMD5", null);
        }else{
            params.put("loginPassMD5", DigestUtils.md5Hex(params.get("loginPass").toString()));
        }
        try {
            userService.updateUserInfo(params);
        } catch (Exception e){
            e.printStackTrace();
            return result.build(null,Code.D407);
        }
        return result.build(null, Code.S207);
    }

    /**
     * 查询用户权限下拉框
     *
     * @param token
     * @return
     */
    @GetMapping("/findUsersAccess")
    public Result findUsersAccess(@RequestHeader("token") String token){
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        List<User> userAccessList;
        try{
            userAccessList = userService.findUsersAccess();
        } catch (Exception e){
            e.printStackTrace();
            return result.build(null,Code.D410);
        }
        return result.build(userAccessList, Code.S208);
    }

    @GetMapping("/appsOfAllot")
    public Result findAppsOfAllot(
            @RequestHeader("token") String token) {
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        List<App> appsList;
        try {
            appsList = userService.findAppsOfAllot();
        } catch (Exception e) {
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(appsList, Code.S200);
    }

    @GetMapping("/appsOfAllot/{userId}")
    public Result findAppsOfAllotByUser(
            @RequestHeader("token") String token,
            @PathVariable("userId") String userId) {
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        List<String> appIdsList;
        try {
            appIdsList = userService.findAppsOfAllotByUser(userId);
        } catch (Exception e) {
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(appIdsList, Code.S200);
    }

    @PostMapping("/saveAppToUser")
    public Result saveAppToUser(
            @RequestHeader("token") String token,
            @RequestBody JSONObject params) {
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        List<Map<String,String>> list = new ArrayList<>();
        try{
            userService.deleteAppsOfAllotByUser(params.getString("userId"));
            String appIdsStr = params.getString("appIds").substring(1, params.getString("appIds").length() - 1);
            if (!("".equals(appIdsStr))){
                String[] appIdsArr = appIdsStr.replaceAll(" ","").split(",");
                for (int i = 0; i < appIdsArr.length; i++) {
                    Map<String,String> map = new HashMap<>();
                    map.put("userId",params.getString("userId"));
                    map.put("appId",appIdsArr[i]);
                    list.add(map);
                }
                userService.addAppsOfAllotByUser(list);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(null, Code.S209);
    }
}
